// pages/addfix/addfix.js
const app = getApp()
/* , */
Page({

    /**
     * 页面的初始数据
     */
    data: {
        buildings: [], // 教学楼列表
        rooms: [], // 教室列表
        areaSelected: "请选择区域",
        roomSelected: "请选择教室",
        fixProject: ["计算机多媒体","室内电器","室内教学工具","室内卫生工具"],
        fixProjectSelect: "请选择项目",
        areadetail: "",
        introduceDetail: "",
        name: "",
        phone: "",
        openid: "",
        imageUrl: "",
        showFlag: '1',
        fixProjectTemp: [
            {wid:"1",item:"计算机多媒体"},
            {wid:"2",item:"室内电器"},
            {wid:"3",item:"室内教学工具"},
            {wid:"4",item:"室内卫生工具"}
        ],
        fixProjectSelectId: 0,
        detailAddress: null,
        selectedBuildingId: null, // 选中的教学楼ID
        selectedRoomId: null // 选中的教室ID
    },
  
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        console.log(options);
        this.setData({
            areaSelected: options.build,
            detailAddress: options.roomName
        });
        // 获取教学楼列表
        this.getBuildings();
        
        // 如果是从教室页面跳转过来，自动填充数据
        if (options.buildingId && options.roomId) {
            this.setData({
                selectedBuildingId: options.buildingId,
                selectedRoomId: options.roomId,
                areaSelected: options.buildingName,
                roomSelected: options.roomName
            });
            
            // 获取该教学楼下的教室列表
            this.getRooms(options.buildingId);
        }
    },

    // 获取教学楼列表
    getBuildings() {
        wx.request({
            url: `${app.globalData.baseUrl}/admin/buildings`,
            method: 'GET',
            success: (res) => {
                if (res.data.code === 200) {
                    const buildings = res.data.data.list.map(building => ({
                        value: building.id,
                        text: building.name
                    }));
                    this.setData({ buildings });
                } else {
                    wx.showToast({
                        title: '获取教学楼列表失败',
                        icon: 'none'
                    });
                }
            },
            fail: (err) => {
                console.error('获取教学楼列表失败:', err);
                wx.showToast({
                    title: '网络错误',
                    icon: 'none'
                });
            }
        });
    },

    // 获取教室列表
    getRooms(buildingId) {
        wx.request({
            url: `${app.globalData.baseUrl}/admin/rooms`,
            method: 'GET',
            data: {
                buildingId: buildingId,
                page: 1,
                pageSize: 100
            },
            success: (res) => {
                if (res.data.code === 200) {
                    const rooms = res.data.data.list.map(room => ({
                        value: room.id,
                        text: room.name
                    }));
                    this.setData({ 
                        rooms,
                        roomSelected: this.data.roomSelected || "请选择教室",
                        selectedRoomId: this.data.selectedRoomId || null
                    });
                } else {
                    wx.showToast({
                        title: '获取教室列表失败',
                        icon: 'none'
                    });
                }
            },
            fail: (err) => {
                console.error('获取教室列表失败:', err);
                wx.showToast({
                    title: '网络错误',
                    icon: 'none'
                });
            }
        });
    },

    /* 报修区域 */
    bindPickerChange(e) {
        const index = e.detail.value;
        const selected = this.data.buildings[index];
        this.setData({
            areaSelected: selected.text,
            selectedBuildingId: selected.value,
            rooms: [], // 清空教室列表
            roomSelected: "请选择教室",
            selectedRoomId: null
        });
        // 获取该教学楼下的教室列表
        this.getRooms(selected.value);
    },

    /* 选择教室 */
    bindRoomChange(e) {
        const index = e.detail.value;
        const selected = this.data.rooms[index];
        this.setData({
            roomSelected: selected.text,
            selectedRoomId: selected.value
        });
    },

    /* 选择维修项目 */
    bindPickerChangePrj(e){
        console.log(e.detail.value);
        console.log(this.data.fixProject);
        var item = this.data.fixProject[e.detail.value]
        var wid = this.data.fixProjectTemp[e.detail.value].wid
        console.log(item,"wid",wid);
        this.setData({
            fixProjectSelect:item,
            fixProjectSelectId:wid
        })
    },
    /* 报修区域 */
    areaDetailInput(e){
        console.log(e.detail.value);
        this.setData({
            areadetail:e.detail.value
        })
    },
     /* 描述详细 */
     introduceDetailInput(e){
        console.log(e.detail.value);
        this.setData({
            introduceDetail:e.detail.value
        })
    },
    /* 姓名 */
    nameInput(e){
        console.log(e.detail.value);
        this.setData({
            name:e.detail.value
        })
    },
    /* 手机号 */
    phoneInput(e){
        console.log(e.detail.value);
        this.setData({
            phone:e.detail.value
        })
    },
    /* 选择照片 */
    bindchoose(){
        wx.chooseMedia({
            count:1,
            sourceType: ['album', 'camera'],
            camera: 'back',
            success:(res)=>{
                /* console.log(res); */
                wx.showLoading({
                  title: '上传中',
                })
                const tempFilePath = res.tempFiles[0].tempFilePath
                console.log(tempFilePath);
                wx.uploadFile({
                  filePath: tempFilePath,
                  name: 'file',
                  url: app.globalData.baseUrl+'/admin/repair/upload',
                  success:(res_1)=>{
                    wx.hideLoading()
                    console.log(res_1);
                    try{
                        var urlTemp = JSON.parse(res_1.data)
                        console.log(urlTemp);
                        var entireUrl = urlTemp.data.url
                        this.setData({
                            imageUrl:entireUrl
                        })
                        console.log(this.data.imageUrl);
                    }catch(error){
                        console.log("图片服务器错误");
                        wx.showToast({
                          title: '上传错误',
                          icon:"none"
                        })
                    }
                  },fail:(res_1)=>{
                      wx.hideLoading()
                    console.error(res_1);
                  }
                })
            } 
        })
    },
    /* submit */
    submit(){
        var pattern = /^1[3-9][0-9]{9}$/
        if(this.data.areaSelected=="请选择区域"){
            wx.showToast({
              title: '请选择区域',
              icon:"none"
            })
            return
        }if(this.data.roomSelected=="请选择教室"){
            wx.showToast({
                title: '请选择教室',
                icon:"none"
              })
              return
        }if(this.data.fixProjectSelect=="请选择项目"){
            wx.showToast({
                title: '请选择项目',
                icon:"none"
              })
              return
        }if(this.data.imageUrl.length==0){
            wx.showToast({
              title: '请上传一张照片',
              icon:"none"
            })
        }
        wx.showLoading({
            title:"提交中"
        })
        // 构建报修数据
        const repairData = {
            userId: wx.getStorageSync('userInfo').id,
            buildingId: this.data.selectedBuildingId,
            roomId: this.data.selectedRoomId,
            repairType: this.data.fixProjectSelect,
            description: this.data.introduceDetail,
            images: [this.data.imageUrl]
        };
        wx.request({
          url: `${app.globalData.baseUrl}/admin/repair`,
          method:"POST",
          data: repairData,
          success:(res)=>{
              wx.hideLoading()
              try{
                console.log(res);
                if(res.data.code==200){
                    wx.showToast({
                      title: res.data.msg,
                    })
                    setTimeout(function(){
                        wx.switchTab({
                          url: '/pages/schedule/schedule',
                        })
                    },1000)
                }
              }catch{
                wx.showToast({
                  title: res.data.statusMsg,
                  icon:"error"
                })
              }
          },fail:(res)=>{
              wx.hideLoading()
              console.error(res);
              wx.showToast({
                title: 'serveErorro',
                icon:"error"
              })
          }
        })
    },
    onShow(){
        
    },
    
  })